import ImageOrIcon from '@/components/ImageOrIcon';
import pUnselected from '@/images/cart/unselected.svg';
import { View } from '@tarojs/components';
import React, { useEffect, useState } from 'react';
import AddSubtract from '../AddSubtract';
import DeliveryWay from '../DeliveryWay';
import OffActivity from '../OffActivity';
import ProductImg from '../ProductImg';
import styles from './index.module.scss';

const ProductItem = ({ className, product, goProduct, setSelected, onProductNumChange }) => {
  const { id, optionValue, productReleaseTitle, originPrice, price, num } = product;

  // 商品数量 (延迟上传服务器)
  const [productNum, setProductNum] = useState(num);

  // 规格字段解析
  let optionSelObj = JSON.parse(optionValue);
  let selOptionList = [];
  for (let key in optionSelObj) {
    selOptionList.push(optionSelObj[key]);
  }

  // 商品数量变更
  const handlePurchaseNum = (productId, v) => {
    // 实时变更显示数据
    setProductNum(v);

    // 异步刷新购物车数据
    onProductNumChange(productId, v);
  };

  // 使用服务器数据更新本地
  useEffect(() => {
    setProductNum(product.num);
  }, [product]);

  return (
    <View className={`${styles.ProductItem} ${className}`}>
      <View
        className="select"
        onClick={() => {
          setSelected(id, product?.selected);
        }}
      >
        <ImageOrIcon
          {...{
            className: 'icon',

            name: product?.selected && 'icon_chose',
            size: 30,

            src: pUnselected,
          }}
        />
      </View>

      <ProductImg product={product} goProduct={goProduct} />

      <View className="product-detail">
        <View className="title omit-2">{productReleaseTitle}</View>

        <View className="product-options">
          <View className="option">
            <View className="txt omit-1">{selOptionList.join('、')}</View>
          </View>
        </View>

        {/* <DeliveryWay product={product} /> */}

        <OffActivity product={product} />

        <View className="price-line">
          <View className="price">
            <View className="unit">¥</View>
            <View className="origin-price">{originPrice}</View>
          </View>

          <View className="action">
            <AddSubtract
              {...{
                product,

                value: productNum,
                onChange: (v) => {
                  handlePurchaseNum(id, v);
                },
              }}
            />
          </View>
        </View>

        {product?.isActivity === 1 && (
          <View className="forecast-price customePageStyle">预估到手价¥{price}</View>
        )}
      </View>
    </View>
  );
};

export default ProductItem;
